import React, { useState } from'react';
import './Chuli.less';
import { useNavigate } from'react-router-dom';

interface ProcessData {
  id: string;
  photos: string[];
  videos: string[];
  processingResult: string;
  completedTime: string;
  recordingPerson: string;
  createdAt: string;
}

const Chuli: React.FC = () => {
  const navigate = useNavigate();
  const [photos, setPhotos] = useState<FileList | null>(null);
  const [videos, setVideos] = useState<FileList | null>(null);
  const [processingResult, setProcessingResult] = useState('');
  const [completedTime, setCompletedTime] = useState(new Date().toISOString().split('T')[0]);
  const [recordingPerson, setRecordingPerson] = useState('姓名1');

  const handlePhotoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) setPhotos(e.target.files);
  };

  const handleVideoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) setVideos(e.target.files);
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    // 弹出确认审核通过的弹窗
    if (!window.confirm('确定要审核通过吗？')) {
      return;
    }
    // 转换照片和视频为Base64
    const photoUrls: string[] = [];
    const videoUrls: string[] = [];

    if (photos) {
      Array.from(photos).forEach(photo => {
        const reader = new FileReader();
        reader.readAsDataURL(photo);
        reader.onload = () => {
          photoUrls.push(reader.result as string);
        };
      });
    }

    if (videos) {
      Array.from(videos).forEach(video => {
        const reader = new FileReader();
        reader.readAsDataURL(video);
        reader.onload = () => {
          videoUrls.push(reader.result as string);
        };
      });
    }

    // 创建处理记录
    const newRecord: ProcessData = {
      id: Date.now().toString(),
      photos: photoUrls,
      videos: videoUrls,
      processingResult,
      completedTime,
      recordingPerson,
      createdAt: new Date().toISOString()
    };

    // 保存到localStorage
    const existingRecords = JSON.parse(localStorage.getItem('processRecords') || '[]');
    localStorage.setItem('processRecords', JSON.stringify([...existingRecords, newRecord]));

    // 跳转到审核页面
    navigate('/service/layout/shenchu');
  };

  return (
    <div className="container">
      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <button onClick={() => navigate('/service/layout/gongdan')}>返回</button>
      </div>
      <br />
      <div className="header">
        <div className="blue-bar" style={{ 'background-color': '#e9ecef' }}>上报处理结果</div>
        <div className="gray-bar" style={{ 'background-color': '#007bff' }}>审核处理结果</div>
      </div>
      <hr />
      <br />
      <div>
        <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;设备名称：1号闸门</p>
        <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;设备类型：闸泵站</p>
        <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;所属工程：闸1</p>
        <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;异常类型：电压不足</p>
        <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;状态：待审核</p>
      </div>
      <br />
      <br />
      <hr />
      <div className="photo-container">
        {photos && Array.from(photos).map((photo, index) => (
          <img key={index} src={URL.createObjectURL(photo)} alt={`photo-${index}`} />
        ))}
        {videos && Array.from(videos).map((video, index) => (
          <video key={index} src={URL.createObjectURL(video)} controls />
        ))}
        <input type="file" accept="image/*" multiple onChange={handlePhotoUpload} />
        <input type="file" accept="video/*" multiple onChange={handleVideoUpload} />
      </div>
      <textarea
        placeholder="请输入处理原因，建议500字以内"
        value={processingResult}
        onChange={(e) => setProcessingResult(e.target.value)}
      />
      <div className="info">
        <div>
          <label>完成时间：</label>
          <input
            type="date"
            value={completedTime}
            onChange={(e) => setCompletedTime(e.target.value)}
          />
        </div>
        <div>
          <label>记录人员：</label>
          <input
            type="text"
            value={recordingPerson}
            onChange={(e) => setRecordingPerson(e.target.value)}
          />
        </div>
      </div>
      <div className="actions">
        <button type="button" onClick={() => {
          if (window.confirm('确定要驳回吗？')) {
            navigate('/service/layout/gongdan');
          }
        }}>驳回</button>
        <button type="button" onClick={handleSubmit}>审核通过</button>
      </div>
    </div>
  );
};

export default Chuli;